<template>
  <el-form inline ref="ruleFormRef" :model="ruleForm" :rules="rules" :label-width="labelWidth" :inline="inline"
    :label-position="labelPosition" class="ruleform-components">

    <el-descriptions :column="2" border>
      <template v-for="item in formRealList">

        <el-descriptions-item>
          <template #label>
            <span>{{ item.label }} <span v-if="item.required" style="color: red;">*</span></span>
          </template>

          <el-form-item v-if="item.formType == 'text'" :style="{ width: formItemWidth }" :prop="item.prop" :rules="[
            {
              required: item.required ? item.required : false,
              message: item.rulesMessage || '请输入...',
              trigger: item.trigger || 'blur',
            },
          ]">
            <el-input :size="formSize" :disabled="item.disabled" :placeholder="item.placeholder || '请输入..'"
              :style="{ width: inputWidth }" v-model="ruleForm[item.prop]" />
          </el-form-item>
          <el-form-item v-else-if="item.formType == 'textarea'" :style="{ width: formItemWidth }" :prop="item.prop"
            :rules="[
              {
                required: item.required ? item.required : false,
                message: item.rulesMessage || '请输入',
                trigger: item.trigger || 'blur',
              },
            ]">
            <el-input :size="formSize" :disabled="item.disabled" type="textarea" :autosize="item.autosize"
              :rows="item.rows || 2" :placeholder="item.placeholder || '请输入..'" :style="{ width: inputWidth }"
              v-model="ruleForm[item.prop]" />
          </el-form-item>
          <el-form-item v-else-if="item.formType == 'radio'" :style="{ width: formItemWidth }" :prop="item.prop" :rules="[
            {
              required: item.required ? item.required : false,
              message: item.rulesMessage || '请选择...',
              trigger: item.trigger || 'change',
            },
          ]">
            <el-radio-group :size="formSize" :disabled="item.disabled" v-model="ruleForm[item.prop]">
              <el-radio :style="item.style" v-for="ele in item.termList" :label="ele.value">
                {{ ele.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-else-if="item.formType == 'checkbox'" :style="{ width: formItemWidth }" :prop="item.prop"
            :rules="[
              {
                required: item.required ? item.required : false,
                message: item.rulesMessage || '请选择...',
                trigger: item.trigger || 'change',
              },
            ]">
            <el-checkbox-group :size="formSize" :disabled="item.disabled" v-model="ruleForm[item.prop]">
              <el-checkbox :style="item.style" v-for="ele in item.termList" :label="ele.value">
                {{ ele.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item v-else-if="item.formType == 'select'" :style="{ width: formItemWidth }" :prop="item.prop"
            :rules="[
              {
                required: item.required ? item.required : false,
                message: item.rulesMessage || '请选择...',
                trigger: item.trigger || 'change',
              },
            ]">
            <el-select :size="formSize" :disabled="item.disabled" :placeholder="item.placeholder || '请选择..'"
              :style="{ width: inputWidth }" v-model="ruleForm[item.prop]" :multiple="item.multiple"
              :filterable="item.filterable || true" :clearable="item.clearable || true">
              <el-option v-for="ele in item.termList" :key="ele.value" :label="ele.name" :value="ele.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="item.formType == 'customer'" :style="{ width: formItemWidth }" :prop="item.prop"
            :rules="[
              {
                required: item.required ? item.required : false,
                message: item.rulesMessage || '请选择...',
                trigger: item.trigger || 'change',
              },
            ]">
            <el-select :size="formSize" :disabled="item.disabled" :placeholder="item.placeholder || '请选择..'"
              :style="{ width: inputWidth }" v-model="ruleForm[item.prop]" :multiple="item.multiple"
              :filterable="item.filterable || true" :clearable="item.clearable || true"
              :remote-method="getDefaultCustomerList">
              <el-option v-for="ele in item.termList" :key="ele.value" :label="ele.name" :value="ele.value" />
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="item.formType == 'region'" :style="{ width: formItemWidth }" :prop="item.prop"
            :rules="[
              {
                required: item.required ? item.required : false,
                message: item.rulesMessage || '请选择...',
                trigger: item.trigger || 'change',
              },
            ]">
            <el-cascader :style="{ width: inputWidth }" v-model="ruleForm[item.prop]" :options="item.termList"
              :props="{ checkStrictly: true, value: 'text', label: 'text', children: 'children' }" clearable
              filterable />
          </el-form-item>
          <el-form-item v-else-if="item.formType == 'date' || item.formType == 'datetime'"
            :style="{ width: formItemWidth }" :prop="item.prop" :rules="[
              {
                required: item.required ? item.required : false,
                message: item.rulesMessage || '请选择...',
                trigger: item.trigger || 'change',
              },
            ]">
            <el-date-picker :disabled="item.disabled" :style="{ width: inputWidth }" v-model="ruleForm[item.prop]"
              :type="item.type || 'date'" :placeholder="item.placeholder || '请选择...'" :size="formSize"
              :start-placeholder="item.startPlaceholder" :end-placeholder="item.endPlaceholder"
              :value-format="item.valueFormat || 'YYYY-MM-DD'" />
          </el-form-item>
          <div :style="{ width: formItemWidth }" v-loading="loading" element-loading-text="上传中..."
            v-else-if="item.formType == 'img'">
            <el-form-item :style="{ width: formItemWidth }" :prop="item.prop" :rules="[
              {
                required: item.required ? item.required : false,
                message: item.rulesMessage || '请上传图片',
                trigger: item.trigger || 'change',
              },
            ]">
              <div class="img-box" v-for="(item, i) in imgList" :key="i">
                <img :src="item.url" alt="" />

                <div class="occlusion">
                  <el-icon class="del" @click="coverRemove(i)">
                    <IEpDelete />
                  </el-icon>
                </div>
              </div>
              <el-upload action="#" list-type="picture-card" :auto-upload="false" :show-file-list="false"
                :file-list="imgList" :on-change="onChange">
                <el-icon>
                  <IEpPlus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </div>
        </el-descriptions-item>

      </template>
    </el-descriptions>
    <div v-if="btnType" style="width: 100% !important; text-align: center;margin-top: 20px;">
      <el-button @click="resetForm">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
    </div>
  </el-form>
</template>
<script setup>

import {
  searchForCustomer
} from "@/plugins/api/customer/setup/fifth";
import { uploadImgApi } from "@/plugins/api/upload";
import { ElMessage } from "element-plus";
import { events } from "@/plugins/eventBus";
const props = defineProps({
  labelWidth: {
    type: [String, Number],
    default: "",
  },
  formList: {
    type: Array,
    default: [],
  },
  formItemWidth: {
    type: String,
    default: "100%",
  },
  inputWidth: {
    type: String,
    default: "100%",
  },
  inline: {
    type: Boolean,
    default: true,
  },
  labelPosition: {
    type: String,
    default: "right",
  },
  formSize: {
    type: String,
    default: "default",
  },
  btnType: {
    type: Boolean,
    default: false,
  },
  validCatch: {
    type: String,
    default: "有未填写的选项！",
  },
  // 标识，区分多个表单同时提交
  identifying: {
    type: [String || Number],
    default: "",
  },
});

let ruleForm = ref({});
let formRealList = ref([]);
let rules = {};
// 上传图片
let imgList = ref([]);
let loading = ref(false);
function onChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  loading.value = true;
  uploadImgApi(formData)
    .then((data) => {
      let obj = {
        url: import.meta.env.VITE_APP_BASE_API + data.file_url,
      };

      imgList.value.push(obj);
      if (!ruleForm.value.imgList && !Array.isArray(ruleForm.value.imgList)) {
        ruleForm.value.imgList = [];
      }
      ruleForm.value.imgList.push(data.file_url);
      loading.value = false;

      //
    })
    .catch(() => {
      loading.value = false;
    });
}



// 获取客户列表
function getDefaultCustomerList(keyword) {
  loading.value = true;
  searchForCustomer({ keyword: keyword }).then((data) => {
    if (formRealList.value) {
      formRealList.value.forEach((item) => {
        if (item.field_id == id) {
          item.termList = data.map((ele) => {
            return {
              name: ele.name,
              value: ele.id,
            };
          });
        }
      });
    }

    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

function coverRemove(index) {
  imgList.value.splice(index, 1);
  ruleForm.value.imgList.splice(index, 1);
}
let ruleFormRef = ref(null);
function initFun() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
  imgList.value = [];
  ruleForm.value = {};
  formRealList.value = [];
  if (props.formList && props.formList.length) {
    formRealList.value = props.formList
  }
  formRealList.value.forEach((item) => {
    if (item.default_value) {
      ruleForm.value[item.prop] = item.default_value;
    }
  });
}
function updateFun(row) {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
  imgList.value = [];
  ruleForm.value = {};
  formRealList.value = [];
  if (props.formList && props.formList.length) {
    formRealList.value = props.formList
  }
  formRealList.value.forEach((item) => {
    ruleForm.value[item.prop] = row[item.prop];
  });
  if (row.imgList) {
    imgList.value = row.imgList.map((ele) => {
      return ele;
    });
  }
}

function submitForm() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      emit("submitFun", ruleForm.value);
      events.emit(
        "formSubmission",
        Object.assign({ identifying: props.identifying }, ruleForm.value)
      );
    } else {
      ElMessage.warning(props.validCatch);
      events.emit("formValidFun");
    }
  });
}
function resetForm() {
  emit("closeForm");
}
const emit = defineEmits(["submitFun", "closeForm"]);
defineExpose({
  initFun,
  submitForm,
  updateFun,
});
onMounted(() => {
  events.on("submitForm", (message) => {
    submitForm();
  });
});
onBeforeUnmount(() => {
  // events.off("submitForm");
});
</script>
<style scoped lang="scss">
.ruleform-components {
  .el-form-item {
    display: flex;
    --font-size: 14px;
    margin-bottom: 0;
  }

  .img-box {
    display: inline-block;
    margin-right: 5px;
    // margin-bottom: 10px;
    width: 148px;
    position: relative;

    img {
      width: 100%;
      height: 140px;
      object-fit: cover;
    }

    .occlusion {
      display: none;
      width: 100%;
      height: 140px;
      background: #9e9c9c75;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
      text-align: center;

      .del {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        line-height: 148px;
        color: #464444;
        cursor: pointer;
        font-size: large;

        &:hover {
          color: rgb(130, 131, 133);
        }
      }
    }

    &:hover {
      .occlusion {
        display: block;
      }
    }
  }
}
</style>
